package com.dxd.onlineshop.controller;

import com.dxd.onlineshop.pojo.Cart;
import com.dxd.onlineshop.pojo.Result;
import com.dxd.onlineshop.pojo.User;
import com.dxd.onlineshop.service.UserService;
import com.dxd.onlineshop.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/update")
public class UpdateController {

    @Autowired
    private UserService userService;

    //修改用户信息
    @PatchMapping("/userInfo")
    public Result<User> updateUserInfo(@RequestBody User user, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        try {
            User updatedUser = userService.updateUserInfo(user, token);
            return Result.success("用户信息修改成功", updatedUser);
        } catch (Exception e) {
            return Result.error("修改失败: " + e.getMessage());
        }
    }

    // 扣除余额
    @PostMapping("/deduct-balance")
    public Result<String> deductBalance(@RequestParam int amount, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Integer userId = (Integer) claims.get("userId");
            boolean deducted = userService.deductBalance(userId, amount);
            if (deducted) {
                return Result.success("余额扣除成功");
            } else {
                return Result.error("余额扣除失败，可能余额不足");
            }
        } catch (Exception e) {
            return Result.error("扣除余额失败: " + e.getMessage());
        }
    }

    // 增加余额（充值）
    @PostMapping("/add-balance")
    public Result<String> addBalance(@RequestParam int amount, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Integer userId = (Integer) claims.get("userId");
            boolean added = userService.addBalance(userId, amount);
            if (added) {
                return Result.success("余额充值成功");
            } else {
                return Result.error("余额充值失败");
            }
        } catch (Exception e) {
            return Result.error("充值失败: " + e.getMessage());
        }
    }

    //增加购物车商品数量
    @PatchMapping("/cart/quantity")
    public Result<String> updateCartItemQuantity(
            @RequestParam Integer cartId,
            @RequestParam Integer quantity,
            HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        System.out.println("Received request to update cart item quantity");
        System.out.println("cartId: " + cartId);
        System.out.println("quantity: " + quantity);
        System.out.println("token: " + token);
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Integer userId = (Integer) claims.get("userId");
            System.out.println("userId: " + userId);
            boolean updated = userService.updateCartItemQuantity(userId, cartId, quantity);
            if (updated) {
                return Result.success("购物车商品数量更新成功");
            } else {
                return Result.error("购物车商品数量更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    //删除商品
    @DeleteMapping("/cart/item")
    public Result<String> removeCartItem(
            @RequestParam Integer cartId,
            HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Integer userId = (Integer) claims.get("userId");
            boolean removed = userService.removeCartItem(userId, cartId);
            if (removed) {
                return Result.success("购物车商品删除成功");
            } else {
                return Result.error("购物车商品删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    //清空购物车
    @DeleteMapping("/cart")
    public Result<String> removeCart(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Integer userId = (Integer) claims.get("userId");
            boolean removed = userService.removeCart(userId);
            if (removed) {
                return Result.success("购物车清除成功");
            }else {
                return Result.error("购物车清除失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("清空失败:" + e.getMessage());
        }
    }

    //添加商品
    @PostMapping("/cart/item")
    public Result<Cart> addCartItem(
            @RequestParam Integer productId,
            @RequestParam Integer quantity,
            HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Integer userId = (Integer) claims.get("userId");
            System.out.println("拿到" + userId);
            Cart addedItem = userService.addCartItem(userId, productId, quantity);
            if (addedItem != null) {
                return Result.success("商品添加到购物车成功", addedItem);
            } else {
                return Result.error("商品添加到购物车失败,添加的商品不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加失败: " + e.getMessage());
        }
    }

}